package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.util.StringUtil;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;
    /*
     * 统计营业额
     */
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        for (LocalDate date = begin; !date.equals(end) ; date = date.plusDays(1)) {
            dateList.add(date);
        }dateList.add(end);
         List<Double> turnoverList = new ArrayList<>();
        for ( LocalDate date : dateList){
            // 查询指定日期的营业额 已完成订单合计
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            // select sum(amount) from orders where order_time > beginTime and  order_time < endTime and status = 5
            Map map= new HashMap();
            map.put("beginTime", beginTime);
            map.put("endTime", endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover = orderMapper.sumByMap(map);
            turnover =  turnover == null ? 0.0 : turnover;
            turnoverList.add( turnover);
        }
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }
    /*
      * 统计用户数量
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        //日期
        List<LocalDate> dateList = new ArrayList<>();
        for (LocalDate date = begin; !date.equals(end) ; date = date.plusDays(1)) {
            dateList.add(date);
        }dateList.add(end);
        //用户总量  每天结束的用户总量 select count(id) from user where createTime < endTime
        List<Integer> totalUserList = new ArrayList<>();
        for (LocalDate date : dateList){
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Integer totalUser = userMapper.countByMap(endTime);
            totalUserList.add(totalUser);
        }
        // 新增用户数量 每天新增的用户数量
        List<Integer> newUserList = new ArrayList<>();
        for (LocalDate date : dateList){
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Integer newUser = userMapper.newCountByMap(beginTime, endTime);
            newUserList.add(newUser);
        }
        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .build();
    }
    /*
     * 统计订单数量
     */
    @Override
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        //日期
        List<LocalDate> dateList = new ArrayList<>();
        for (LocalDate date = begin; !date.equals(end);date=date.plusDays(1)){
            dateList.add(date);
        }dateList.add(end);
        //每日订单数
        List<Integer> orderCountList = new ArrayList<>();
        for (LocalDate date : dateList){
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map= new HashMap();
            map.put("beginTime", beginTime);
            map.put("endTime", endTime);
            map.put("status", null);
            Integer  orderCount = orderMapper.countByMap(map);
            orderCountList.add(orderCount);
        }
        //每日有效订单数
        List<Integer> validOrderCountList = new ArrayList<>();
        for (LocalDate date : dateList){
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map= new HashMap();
            map.put("beginTime", beginTime);
            map.put("endTime", endTime);
            map.put("status", Orders.COMPLETED);
            Integer validOrderCount = orderMapper.countByMap(map);
            validOrderCountList.add(validOrderCount);
        }
        //订单总数
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        //有效订单数
        Integer validOrderCount =validOrderCountList.stream().reduce(Integer::sum).get();
        //订单完成率
        Double orderCompletionRate = 0.0;
        if (totalOrderCount != 0)
                orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }
    /*
    Top10
     */
    @Override
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end) {
            //select od.name,sum(od.number) s from order_detail od,orders o where od.order_id=o.id and o.status = 5 and o.order_time > '2020-10-01' and o.order_time < '2025-10-01'
        //group by od.name order by s desc
        //商品名称列表，以逗号分隔，例如：鱼香肉丝,宫保鸡丁,水煮鱼
        List<String> nameList = new ArrayList<>();
        List<String> numberList = new ArrayList<>();
        List<GoodsSalesDTO> list = new ArrayList<>();
        LocalDateTime  beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime  endTime = LocalDateTime.of(end, LocalTime.MAX);
        list = orderMapper.getListByStatusAndOrderTime(beginTime, endTime);

        for (GoodsSalesDTO goodsSalesDTO : list) {
            nameList.add(goodsSalesDTO.getName());
            numberList.add(goodsSalesDTO.getNumber().toString());
        }
        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList, ","))
                .numberList( StringUtils.join(numberList, ","))
                .build();
    }
    /*
    导出数据
     */
    @Override
    public void export(HttpServletResponse response) {
        // 1. 查询数据库，获取到所有的数据 最近一个月的
        LocalDate databegin = LocalDate.now().minusDays(30);
        LocalDate dataend = LocalDate.now().minusDays(1);
        BusinessDataVO data = workspaceService.getBusinessData(LocalDateTime.of(databegin, LocalTime.MIN), LocalDateTime.of(dataend, LocalTime.MAX));
        //  2. 将数据写入excel表格
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            //  创建excel
            XSSFWorkbook excel = new XSSFWorkbook(in);
            XSSFSheet sheet1 = excel.getSheet("Sheet1");
            //填充数据
            sheet1.getRow(1).getCell(1).setCellValue(databegin + "至" + dataend);
            XSSFRow row = sheet1.getRow(3);
            row.getCell(2).setCellValue(data.getTurnover());
            row.getCell(4).setCellValue(data.getOrderCompletionRate());
            row.getCell(6).setCellValue(data.getNewUsers());
            row = sheet1.getRow(4);
            row.getCell(2).setCellValue(data.getValidOrderCount());
            row.getCell(4).setCellValue(data.getUnitPrice());
            //  4. 填充明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = databegin.plusDays(i);
                // 查询数据
                BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                XSSFRow row1 = sheet1.getRow(7 + i);
                row1.getCell(1).setCellValue(date.toString());
                row1.getCell(2).setCellValue(businessData.getTurnover());
                row1.getCell(3).setCellValue(businessData.getValidOrderCount());
                row1.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row1.getCell(5).setCellValue(businessData.getUnitPrice());
                row1.getCell(6).setCellValue(businessData.getNewUsers());

            }
            //  3. 通过输出流下载excel表格
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);
            //  关闭流
            out.close();
            excel.close();
        }catch (IOException e){
            e.printStackTrace();
        }

    }
}
